package com.xpc.starter.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.xpc.starter.handler.DataPermissionHandler;
import com.xpc.starter.interceptor.DataPermissionInterceptor;
import com.xpc.starter.service.DataPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：mybatisplus配置类
 *
 * @author xpc on 2024/4/3 10:11
 */
// 注入这个bean是开启数据权限拦截器
@ConditionalOnBean(DataPermissionService.class)
@Configuration
// 扫描权限拦截器的bean
@ComponentScan(basePackages = "com.xpc.starter")
// 开启注解拦截
@EnableAspectJAutoProxy
@Slf4j
public class MybatisAutoConfiguration {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        return new MybatisPlusInterceptor();
    }

    @Resource
    private DataPermissionHandler myPermissionHandler;

    @Bean
    public DataPermissionInterceptor dataPermissionInterceptor(MybatisPlusInterceptor mybatisPlusInterceptor) {
        DataPermissionInterceptor dataPermissionInterceptor = new DataPermissionInterceptor();
        dataPermissionInterceptor.setDataPermissionHandler(myPermissionHandler);
        List<InnerInterceptor> list = new ArrayList<>();
        // 添加数据权限插件
        list.add(dataPermissionInterceptor);
        // 分页插件
        list.add(new PaginationInnerInterceptor(DbType.MYSQL));
        mybatisPlusInterceptor.setInterceptors(list);
        return dataPermissionInterceptor;
    }

    public MybatisAutoConfiguration() {
        log.info("DataPermissionAutoConfiguration 配置类初始化 ......");
    }
}
